package com.jiuyou.websocket.interceptor;

import com.alibaba.fastjson.JSON;
import com.ruoyi.common.core.domain.entity.Member;
import com.ruoyi.common.core.domain.entity.StoreUser;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.*;
import org.springframework.web.socket.server.HandshakeInterceptor;

import javax.servlet.http.HttpServletRequest;
import java.nio.charset.StandardCharsets;
import java.util.Map;

@Component
public class WebSocketInterceptor implements HandshakeInterceptor {

    private final Logger log = LoggerFactory.getLogger(WebSocketInterceptor.class);



    @Override
    public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception {
        log.info("webSocket握手");

        if (request instanceof ServletServerHttpRequest) {
            ServletServerHttpRequest serverRequest = (ServletServerHttpRequest) request;
            HttpServletRequest httpServletRequest = serverRequest.getServletRequest();
            //获取用户的openId
            String openId = httpServletRequest.getHeader("openId");
            String platform = httpServletRequest.getHeader("platform");
            if (null != openId) {
                openId = new String(openId.getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8);
                attributes.put("openId", openId);
                attributes.put("platform", platform);


            } else {
                log.error("获取到请求头中【openId：null】！");
            }
        }

        return true;
    }

    @Override
    public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Exception ex) {

    }

}
